package com.mxpio.erp.workshop.controller;

import com.mxpio.erp.common.enums.NoticeStatusEnums;
import com.mxpio.erp.common.jpa.model.Notice;
import com.mxpio.erp.common.order.policy.NoticeContext;
import com.mxpio.erp.common.order.service.NoticeService;
import com.mxpio.erp.common.technology.entity.Item;
import com.mxpio.erp.common.technology.service.ItemService;
import com.mxpio.erp.common.vo.OrderExcuteVo;
import com.mxpio.erp.common.workshop.entity.DefectiveProductsNotice;
import com.mxpio.erp.common.workshop.entity.DefectiveProductsNoticeLine;
import com.mxpio.erp.common.workshop.service.DefectiveProductsNoticeService;
import com.mxpio.erp.workshop.policy.impl.DefaultDefectiveNoticePolicy;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.CrudType;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Tag(name = "DefectiveProductsNoticeController", description = "不良品处理通知单接口")
@RestController
@RequestMapping("/erp/workshop/dp/")
public class DefectiveProductsNoticeController {

    @Autowired
    private DefectiveProductsNoticeService service;

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private ItemService itemService;



    @GetMapping("list")
    @Operation(summary = "不良品处理通知单列表", description = "获取不良品处理通知单列表（无分页）", method = "GET")
    public Result<List<DefectiveProductsNotice>> list(@Parameter(description="查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<DefectiveProductsNotice> moPickingNotice = service.list(DefectiveProductsNotice.class, criteria);
        return Result.OK(moPickingNotice);
    }

    @GetMapping("page")
    @Operation(summary = "不良品处理通知单列表", description = "获取不良品处理通知单列表（分页）", method = "GET")
    public Result<Page<DefectiveProductsNotice>> page(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<DefectiveProductsNotice> moPickingNotice = service.listPage(DefectiveProductsNotice.class, page, criteria);
        return Result.OK(moPickingNotice);
    }

    @GetMapping("list/{noticeNo}")
    @Operation(summary = "根据noticeNo获取不良品处理通知单", description = "根据noticeNo获取不良品处理通知单", method = "GET")
    public Result<DefectiveProductsNotice> getById(@Parameter(description="业务单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
        DefectiveProductsNotice moPickingNotice = service.getById(DefectiveProductsNotice.class, noticeNo);
        return Result.OK(moPickingNotice);
    }

    @RequestMapping("save")
    @Operation(summary = "保存不良品处理通知单", description = "保存不良品处理通知单")
    @Transactional
    public Result<DefectiveProductsNotice> save(@RequestBody DefectiveProductsNotice notice) {
        if (CrudType.SAVE.equals(notice.getCrudType())){
            notice.setNoticeDate(new Date());
            //notice.setAccessType(OrderEnums.AccessType.OUT.getCode());
            //notice.setPickingType(NoticeStatusEnums.NoticeType.MO_M_OUT.getCode());//由于领/退/ 对应同一个结果，故业务类型由前端往后端传
            if (StringUtils.equals(NoticeStatusEnums.NoticeType.MO_M_OUT.getCode(),notice.getPickingType())){//生产领料 通知单新增时，由于需要占用，所以通知单状态默认为草稿
                notice.setNoticeStatus(NoticeStatusEnums.NoticeStatus.DRAFT.getStatusCode());//新增默认为草稿状态，此处覆盖前端可能传递的开立状态值
            }
            List<DefectiveProductsNoticeLine> moPickingNoticeLines = notice.getDefectiveProductsNoticeLines();
            for(DefectiveProductsNoticeLine line : moPickingNoticeLines) {
                Item item = itemService.getById(Item.class,line.getItemCode());
                line.setItemName(item.getItemName());
                line.setItemSpec(item.getItemSpec());
                line.setUnitCode(item.getUnitCode());
            }
        }else{
            List<DefectiveProductsNoticeLine> moPickingNoticeLines = notice.getDefectiveProductsNoticeLines();
            for(DefectiveProductsNoticeLine line : moPickingNoticeLines) {
                if (CrudType.SAVE.equals(line.getCrudType())){
                    Item item = itemService.getById(Item.class,line.getItemCode());
                    line.setItemName(item.getItemName());
                    line.setItemSpec(item.getItemSpec());
                    line.setUnitCode(item.getUnitCode());
                }
            }
        }

        service.save(notice,new SmartCrudPolicyAdapter(){
            @Override
            public boolean beforeInsert(CrudContext context) {
                Object o = context.getEntity();
                if(o instanceof DefectiveProductsNoticeLine){
                    DefectiveProductsNotice moPickingNotice = context.getParent();
                    ((DefectiveProductsNoticeLine) o).setNoticeNo(moPickingNotice.getNoticeNo());
                }
                return true;
            }
        });
        return Result.OK(notice);
    }
    
    @RequestMapping("excute/{noticeNo}")
    @Operation(summary = "通知单执行", description = "通知单执行")
    @Transactional
    public Result<Object> excute(@PathVariable(name = "noticeNo", required = true) String noticeNo, 
    		@RequestBody OrderExcuteVo orderExcuteVo) {
    	DefectiveProductsNotice notice = service.getById(DefectiveProductsNotice.class, noticeNo);
        if (org.apache.commons.lang3.StringUtils.equals(notice.getNoticeStatus(),NoticeStatusEnums.NoticeStatus.CONFIRM.getStatusCode())){
            return Result.error("单据状态已发生变化，已确认状态单据不允许重复确认");
        }
    	NoticeContext context = noticeService.execute(notice, new DefaultDefectiveNoticePolicy(orderExcuteVo.getLines()));
    	if(CollectionUtils.isEmpty(context.getErrors())) {
    		return Result.OK();
    	}else {
    		return Result.error(context.getErrors().get(0));
    	}
    }


    @DeleteMapping("remove/{noticeNos}")
    @Operation(summary = "根据noticeNo删除不良品处理通知单", description = "删除不良品处理通知单", method = "DELETE")
    @Transactional
    public Result<DefectiveProductsNotice> remove(@Parameter(description="业务单号，多个单号用英文逗号分隔") @PathVariable(name = "noticeNos", required = true) String noticeNos) {
        String[] noticeNo = noticeNos.split(",");
        for(String key : noticeNo){
            service.delete(DefectiveProductsNotice.class, key);
        }
        return Result.OK();
    }
    
    @PutMapping("reject/{noticeNo}")
    @Operation(summary = "拒绝通知单", description = "拒绝通知单", method = "PUT")
    @Transactional
    public Result<? extends Notice> close(@Parameter(description="通知单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
    	DefectiveProductsNotice moPickingNotice = service.getById(DefectiveProductsNotice.class,noticeNo);
    	return noticeService.updateNoticeStatus(moPickingNotice, NoticeStatusEnums.NoticeStatus.REJECT);
    }

    @PutMapping("commit/{noticeNo}")
    @Operation(summary = "提交通知单", description = "提交通知单", method = "PUT")
    @Transactional
    public Result<? extends Notice> commit(@Parameter(description="通知单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
        DefectiveProductsNotice moPickingNotice = service.getById(DefectiveProductsNotice.class,noticeNo);
        if (!StringUtils.equals(moPickingNotice.getNoticeStatus(),NoticeStatusEnums.NoticeStatus.DRAFT.getStatusCode())){
            return Result.error("仅草稿状态的单据可以执行提交操作");
        }
        return noticeService.updateNoticeStatus(moPickingNotice, NoticeStatusEnums.NoticeStatus.CREATE);
    }

/*    @GetMapping("export")
    @Operation(summary = "不良品处理通知单列表导出", description = "获取不良品处理通知单列表导出", method = "GET")
    public Result<List<MoPickingNoticeExportVO>> export(@Parameter(description="查询参数") Criteria criteria){
        List<DefectiveProductsNotice> moPickingNotice = service.list(DefectiveProductsNotice.class, criteria);
        List<MoPickingNoticeExportVO> exportVOList = new ArrayList<>();
        if (moPickingNotice.size()>0){
            for (DefectiveProductsNotice notice:moPickingNotice){
                Criteria c = Criteria.create().addCriterion("noticeNo", Operator.EQ, notice.getNoticeNo());
                c.addOrder(new Order("lineNo",false));//按lineno升序
                List<DefectiveProductsNoticeLine> moPickingNoticeLines = moPickingNoticeLineService.list(DefectiveProductsNoticeLine.class, c);
                if (moPickingNoticeLines.size()>0){
                    for (DefectiveProductsNoticeLine line:moPickingNoticeLines){
                        MoPickingNoticeExportVO exportVO = new MoPickingNoticeExportVO();
                        BeanReflectionUtils.copyProperties(exportVO,notice);
                        BeanReflectionUtils.copyProperties(exportVO,line);
                        exportVOList.add(exportVO);
                    }
                }
            }
        }
        return Result.OK(exportVOList);
    }*/


    @GetMapping("listbynos/{noticeNos}")
    @Operation(summary = "根据noticeNos获取对应通知单及明细", description = "根据noticeNos获取通知单及明细", method = "GET")
    public Result<List<DefectiveProductsNotice>> getByIds(@PathVariable(name = "noticeNos", required = true) String noticeNos) {
        return service.listByIds(noticeNos);
    }
}
